import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controller.dart';

class ServerFilesPage extends GetView<ServerFilesController> {
  const ServerFilesPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () => _showExitConfirmDialog(),
        ),
        title: Obx(() => Text(controller.server.value?.name ?? '文件管理器')),
        actions: [
          // 刷新按钮
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () => controller.refresh(),
            tooltip: '刷新',
          ),
          // 创建目录按钮
          IconButton(
            icon: const Icon(Icons.create_new_folder),
            onPressed: () => controller.createDirectory(),
            tooltip: '创建目录',
          ),
        ],
      ),
      body: Column(
        children: [
          // 路径导航栏
          _buildPathBar(),
          const Divider(height: 1),
          // 快捷目录栏
          _buildQuickAccessBar(),
          const Divider(height: 1),
          // 文件列表
          Expanded(
            child: Obx(() {
              if (controller.isLoading.value && controller.files.isEmpty) {
                return const Center(child: CircularProgressIndicator());
              }

              if (controller.files.isEmpty) {
                return _buildEmptyView();
              }

              return RefreshIndicator(
                onRefresh: controller.refresh,
                child: ListView.builder(
                  padding: const EdgeInsets.all(8),
                  itemCount: controller.files.length,
                  itemBuilder: (context, index) {
                    return _buildFileItem(controller.files[index]);
                  },
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  /// 显示退出确认对话框
  void _showExitConfirmDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('退出文件管理器', style: TextStyle(fontSize: 15)),
        content: const Text('确定要退出文件管理器吗？', style: TextStyle(fontSize: 12)),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back(); // 关闭对话框
              Get.back(); // 退出文件管理器
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('退出'),
          ),
        ],
      ),
    );
  }

  /// 构建快捷目录栏
  Widget _buildQuickAccessBar() {
    final quickDirs = [
      {'name': '根', 'path': '/', 'icon': Icons.home},
      {'name': 'root', 'path': '/root', 'icon': Icons.person},
      {'name': 'home', 'path': '/home', 'icon': Icons.folder_shared},
      {'name': 'etc', 'path': '/etc', 'icon': Icons.settings},
      {'name': 'var', 'path': '/var', 'icon': Icons.storage},
      {'name': 'tmp', 'path': '/tmp', 'icon': Icons.folder_special},
    ];

    return Container(
      color: Colors.white,
      height: 50,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        itemCount: quickDirs.length,
        itemBuilder: (context, index) {
          final dir = quickDirs[index];
          return Obx(() {
            final isActive = controller.currentPath.value == dir['path'];
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6),
              child: InkWell(
                onTap: () {
                  if (!isActive) {
                    controller.goToPath(dir['path'] as String);
                  }
                },
                borderRadius: BorderRadius.circular(8),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    color: isActive ? Colors.blue.shade50 : Colors.grey.shade100,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      color: isActive ? Colors.blue.shade300 : Colors.grey.shade300,
                      width: 1,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        dir['icon'] as IconData,
                        size: 16,
                        color: isActive ? Colors.blue.shade700 : Colors.grey.shade700,
                      ),
                      const SizedBox(width: 6),
                      Text(
                        dir['name'] as String,
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
                          color: isActive ? Colors.blue.shade900 : Colors.grey.shade800,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          });
        },
      ),
    );
  }

  /// 构建路径导航栏
  Widget _buildPathBar() {
    return Container(
      color: Colors.grey.shade100,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Row(
        children: [
          Icon(Icons.folder_outlined, size: 18, color: Colors.orange.shade700),
          const SizedBox(width: 8),
          Expanded(
            child: Obx(() => SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: GestureDetector(
                onTap: () => _showPathDialog(),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(color: Colors.grey.shade300),
                  ),
                  child: Text(
                    controller.currentPath.value,
                    style: const TextStyle(fontSize: 12, fontFamily: 'monospace'),
                  ),
                ),
              ),
            )),
          ),
          const SizedBox(width: 8),
          Obx(() {
            // 只有不在根目录时才显示返回按钮
            if (controller.currentPath.value != '/') {
              return IconButton(
                icon: const Icon(Icons.arrow_upward, size: 20),
                onPressed: () => controller.goBack(),
                tooltip: '返回上级',
                padding: const EdgeInsets.all(4),
                constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
              );
            }
            return const SizedBox.shrink();
          }),
        ],
      ),
    );
  }

  /// 显示路径输入对话框
  void _showPathDialog() {
    final controller = TextEditingController(text: this.controller.currentPath.value);
    Get.dialog(
      AlertDialog(
        title: const Text('跳转到路径', style: TextStyle(fontSize: 15)),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            hintText: '/root/data',
            hintStyle: TextStyle(fontSize: 12),
          ),
          style: const TextStyle(fontSize: 13, fontFamily: 'monospace'),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final path = controller.text;
              Get.back();
              this.controller.goToPath(path);
            },
            child: const Text('跳转'),
          ),
        ],
      ),
    );
  }

  /// 构建空视图
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.folder_open, size: 48, color: Colors.grey.shade400),
          const SizedBox(height: 12),
          const Text(
            '空目录',
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
          if (controller.errorMessage.value.isNotEmpty) ...[
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Text(
                controller.errorMessage.value,
                style: const TextStyle(fontSize: 11, color: Colors.red),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建文件项
  Widget _buildFileItem(FileInfo file) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: InkWell(
        onTap: () {
          if (file.isDirectory) {
            controller.enterDirectory(file);
          } else if (controller.isTextFile(file.name)) {
            // 文本文件直接打开查看
            _showFileViewer(file, readOnly: true);
          } else {
            // 非文本文件显示操作菜单
            _showFileActions(file);
          }
        },
        onLongPress: () {
          // 长按显示操作菜单
          if (!file.isDirectory) {
            _showFileActions(file);
          }
        },
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              // 文件图标
              Icon(
                file.isDirectory ? Icons.folder : _getFileIcon(file.name),
                size: 24,
                color: file.isDirectory ? Colors.orange.shade700 : Colors.blue.shade700,
              ),
              const SizedBox(width: 12),
              // 文件信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      file.name,
                      style: const TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w500,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Row(
                      children: [
                        Text(
                          file.permissions,
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey.shade600,
                            fontFamily: 'monospace',
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          file.owner,
                          style: TextStyle(fontSize: 10, color: Colors.grey.shade600),
                        ),
                        const SizedBox(width: 8),
                        if (!file.isDirectory)
                          Text(
                            file.size,
                            style: TextStyle(fontSize: 10, color: Colors.grey.shade600),
                          ),
                      ],
                    ),
                  ],
                ),
              ),
              // 更多按钮
              IconButton(
                icon: const Icon(Icons.more_vert, size: 18),
                onPressed: () => _showFileActions(file),
                padding: const EdgeInsets.all(4),
                constraints: const BoxConstraints(minWidth: 32, minHeight: 32),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 获取文件图标
  IconData _getFileIcon(String filename) {
    final extension = filename.split('.').last.toLowerCase();
    switch (extension) {
      case 'txt':
      case 'log':
      case 'md':
        return Icons.description;
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return Icons.image;
      case 'mp4':
      case 'avi':
      case 'mov':
        return Icons.video_file;
      case 'mp3':
      case 'wav':
        return Icons.audio_file;
      case 'zip':
      case 'tar':
      case 'gz':
        return Icons.folder_zip;
      case 'sh':
      case 'bash':
        return Icons.terminal;
      case 'js':
      case 'py':
      case 'java':
      case 'dart':
        return Icons.code;
      default:
        return Icons.insert_drive_file;
    }
  }

  /// 显示文件操作菜单
  void _showFileActions(FileInfo file) {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 12),
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(height: 16),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Row(
                children: [
                  Icon(
                    file.isDirectory ? Icons.folder : _getFileIcon(file.name),
                    size: 24,
                    color: file.isDirectory ? Colors.orange.shade700 : Colors.blue.shade700,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          file.name,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          '${file.permissions}  ${file.owner}  ${file.size}',
                          style: TextStyle(fontSize: 10, color: Colors.grey.shade600),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const Divider(height: 24),
            if (file.isDirectory)
              ListTile(
                leading: const Icon(Icons.folder_open, size: 20),
                title: const Text('打开目录', style: TextStyle(fontSize: 13)),
                onTap: () {
                  Get.back();
                  controller.enterDirectory(file);
                },
                dense: true,
              ),
            if (!file.isDirectory && controller.isTextFile(file.name))
              ListTile(
                leading: const Icon(Icons.visibility, size: 20, color: Colors.blue),
                title: const Text('查看', style: TextStyle(fontSize: 13)),
                onTap: () {
                  Get.back();
                  _showFileViewer(file, readOnly: true);
                },
                dense: true,
              ),
            if (!file.isDirectory && controller.isTextFile(file.name))
              ListTile(
                leading: const Icon(Icons.edit_note, size: 20, color: Colors.green),
                title: const Text('编辑', style: TextStyle(fontSize: 13)),
                onTap: () {
                  Get.back();
                  _showFileViewer(file, readOnly: false);
                },
                dense: true,
              ),
            ListTile(
              leading: const Icon(Icons.drive_file_rename_outline, size: 20),
              title: const Text('重命名', style: TextStyle(fontSize: 13)),
              onTap: () {
                Get.back();
                controller.renameFile(file);
              },
              dense: true,
            ),
            ListTile(
              leading: const Icon(Icons.delete_outline, size: 20, color: Colors.red),
              title: const Text('删除', style: TextStyle(fontSize: 13, color: Colors.red)),
              onTap: () {
                Get.back();
                controller.deleteFile(file);
              },
              dense: true,
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
    );
  }

  /// 显示文件查看器/编辑器
  Future<void> _showFileViewer(FileInfo file, {required bool readOnly}) async {
    // 读取文件内容
    final content = await controller.readFileContent(file);
    if (content == null) return;

    final textController = TextEditingController(text: content);
    bool hasChanges = false;

    Get.dialog(
      WillPopScope(
        onWillPop: () async {
          if (!readOnly && hasChanges) {
            final shouldExit = await _showUnsavedChangesDialog();
            return shouldExit ?? false;
          }
          return true;
        },
        child: Dialog(
          insetPadding: const EdgeInsets.all(16),
          child: Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(Get.context!).size.height * 0.85,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题栏
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: readOnly ? Colors.blue.shade50 : Colors.green.shade50,
                    border: Border(
                      bottom: BorderSide(color: Colors.grey.shade300),
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(
                        readOnly ? Icons.visibility : Icons.edit_note,
                        size: 20,
                        color: readOnly ? Colors.blue.shade700 : Colors.green.shade700,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              readOnly ? '查看文件' : '编辑文件',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.bold,
                                color: readOnly ? Colors.blue.shade900 : Colors.green.shade900,
                              ),
                            ),
                            const SizedBox(height: 2),
                            Text(
                              file.name,
                              style: TextStyle(
                                fontSize: 11,
                                color: Colors.grey.shade700,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.close, size: 20),
                        onPressed: () async {
                          if (!readOnly && hasChanges) {
                            final shouldExit = await _showUnsavedChangesDialog();
                            if (shouldExit == true) Get.back();
                          } else {
                            Get.back();
                          }
                        },
                        padding: const EdgeInsets.all(4),
                      ),
                    ],
                  ),
                ),
                // 文件内容编辑区
                Expanded(
                  child: Container(
                    color: Colors.grey.shade900,
                    padding: const EdgeInsets.all(12),
                    child: TextField(
                      controller: textController,
                      readOnly: readOnly,
                      maxLines: null,
                      expands: true,
                      style: const TextStyle(
                        fontSize: 12,
                        fontFamily: 'monospace',
                        color: Colors.white,
                        height: 1.5,
                      ),
                      decoration: const InputDecoration(
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.zero,
                      ),
                      onChanged: (value) {
                        if (!readOnly) hasChanges = true;
                      },
                    ),
                  ),
                ),
                // 底部操作栏
                if (!readOnly)
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border(
                        top: BorderSide(color: Colors.grey.shade300),
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(Icons.info_outline, size: 14, color: Colors.grey.shade600),
                        const SizedBox(width: 6),
                        Text(
                          '${textController.text.length} 字符',
                          style: TextStyle(fontSize: 11, color: Colors.grey.shade600),
                        ),
                        const Spacer(),
                        TextButton(
                          onPressed: () => Get.back(),
                          child: const Text('取消', style: TextStyle(fontSize: 12)),
                        ),
                        const SizedBox(width: 8),
                        ElevatedButton.icon(
                          icon: const Icon(Icons.save, size: 16),
                          label: const Text('保存', style: TextStyle(fontSize: 12)),
                          onPressed: () async {
                            final success = await controller.saveFileContent(
                              file,
                              textController.text,
                            );
                            if (success) {
                              hasChanges = false;
                              Get.back();
                            }
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  /// 显示未保存更改对话框
  Future<bool?> _showUnsavedChangesDialog() {
    return Get.dialog<bool>(
      AlertDialog(
        title: const Text('未保存的更改', style: TextStyle(fontSize: 15)),
        content: const Text(
          '文件有未保存的更改，确定要退出吗？',
          style: TextStyle(fontSize: 12),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('继续编辑'),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('放弃更改'),
          ),
        ],
      ),
    );
  }
}

